#include "head_s.h"


int ls(const user_t* status, const portocol_t* portocol, int net_fd, MYSQL* mysql)
{

    // 获取ls所在的路径
    char path_s[128] = {0};
    recv(net_fd, path_s, sizeof(path_s), MSG_WAITALL);
    // sprintf(path_s, "%s%s%s", status->base_path, status->user_name, status->path);

    if(strlen(path_s) == 1){

    }else{
        path_s[strlen(path_s)-1]=0;
    }


    //获取用户id
    char nameId[1024] = {0};
    // strcpy(name, status->user_name);
    sprintf(nameId, "select id from user_info where name = '%s'", status->user_name);
    mysql_query(mysql, nameId);
    printf("%s\n", mysql_error(mysql));  // 判断正确
    MYSQL_RES* res_usr = mysql_store_result(mysql);
    if(res_usr == 0){
        mysql_error(mysql);
        exit(1);
    }
    MYSQL_ROW row2;
    int usr_id = 0;
    while((row2 = mysql_fetch_row(res_usr))){
        char num[10];
        strncpy(num, row2[0], sizeof(num) - 1);
        num[sizeof(num) - 1] = '\0';
        usr_id = atoi(num);
    }
    mysql_free_result(res_usr);


    // 获得路径 id
    char pathId[1024] = {0};
    sprintf(pathId, "select id from file_info where file_path = '%s' and user_id = %d", path_s, usr_id);
    char num[10];


    mysql_query(mysql, pathId);
    printf("%s\n", mysql_error(mysql));
    MYSQL_RES* res_path = mysql_store_result(mysql);
    if(res_path == 0){
        mysql_error(mysql);
        exit(1);
    }
    MYSQL_ROW row1;
    int path_id = 0;
    while((row1 = mysql_fetch_row(res_path))){
        char id[10] = {0};
        strncpy(id, row1[0], sizeof(id) - 1);
        path_id = atoi(id);
    }
    mysql_free_result(res_path);
    // 根据 路径id 和 用户id 找父id

    // 父id为 uid 的所有文件，除了文件类型为1且exist_flag为0
    char buf2[1024] = {0};
    sprintf(buf2, "select file_name from file_info where p_id = %d and exist_flag = 0", path_id);
    mysql_query(mysql, buf2);
    printf("%s\n", mysql_error(mysql));
    MYSQL_RES* res_file = mysql_store_result(mysql);
    if(res_file == 0){
        mysql_error(mysql);
        exit(1);

    }
    MYSQL_ROW row4;
    char dir[1024] = {0};
    while((row4 = mysql_fetch_row(res_file))){
        if (strlen(dir) > 0) {
            strcat(dir, "    ");                               //
        }
        strcat(dir, row4[0]);
    }
    mysql_free_result(res_file);

    // 传输文件名
    send(net_fd, dir, sizeof(dir), MSG_NOSIGNAL);

}
